package wechat.handler.request.base;

import com.alibaba.fastjson.JSONObject;

import wechat.handler.bean.request.webauth.WebAuthAccesstokenBean;
import wechat.handler.resources.AppFilter;
import wechat.handler.resources.InstanceResource;
import wechat.handler.util.http.HttpClientUtil;

public class BaseWebAuth extends BaseRequest {
	
	protected WebAuthAccesstokenBean getWebAccesstoken(String code) throws Exception {
		String url = super.api_sns_accesstoken.replace("APPID", BaseRequest.Appid).replace("SECRET", BaseRequest.Appsecret).replace("CODE", code);
		String result = HttpClientUtil.get(url);
		
		JSONObject jsonResult = JSONObject.parseObject(result);
		checkResult(jsonResult);
		
		String access_token = jsonResult.getString("access_token");
		String expires_in = jsonResult.getString("expires_in");
		String refresh_token = jsonResult.getString("refresh_token");
		String openid = jsonResult.getString("openid");
		String[] scope = jsonResult.getString("scope").split(",");
		 
		WebAuthAccesstokenBean wAuthAaccesstokenBean = new WebAuthAccesstokenBean();
		wAuthAaccesstokenBean.setAccess_token(access_token);
		wAuthAaccesstokenBean.setExpires_in(expires_in);
		wAuthAaccesstokenBean.setRefresh_token(refresh_token);
		wAuthAaccesstokenBean.setOpenid(openid);
		wAuthAaccesstokenBean.setScope(scope);
		
		return wAuthAaccesstokenBean;
	}
	
	
	protected WebAuthAccesstokenBean getWebAccesstoken(String appid,String code) throws Exception {
		InstanceResource instanceResource = AppFilter.chooseApp(appid);
		
		//String url = super.api_sns_accesstoken.replace("APPID", INS.getValue(appid + ".appid")).replace("SECRET",INS.getValue(appid + ".appsecret")).replace("CODE", code);
		String url = super.api_sns_accesstoken.replace("APPID", instanceResource.getAppid()).replace("SECRET",instanceResource.getAppsecret()).replace("CODE", code);
		String result = HttpClientUtil.get(url);
		
		JSONObject jsonResult = JSONObject.parseObject(result);
		checkResult(jsonResult);
		
		String access_token = jsonResult.getString("access_token");
		String expires_in = jsonResult.getString("expires_in");
		String refresh_token = jsonResult.getString("refresh_token");
		String openid = jsonResult.getString("openid");
		String[] scope = jsonResult.getString("scope").split(",");
		 
		WebAuthAccesstokenBean wAuthAaccesstokenBean = new WebAuthAccesstokenBean();
		wAuthAaccesstokenBean.setAccess_token(access_token);
		wAuthAaccesstokenBean.setExpires_in(expires_in);
		wAuthAaccesstokenBean.setRefresh_token(refresh_token);
		wAuthAaccesstokenBean.setOpenid(openid);
		wAuthAaccesstokenBean.setScope(scope);
		
		return wAuthAaccesstokenBean;
	}
	
	protected String getJSTicket() throws Exception {
		return super.getJSTicket();
	}
	
	protected String getJSTicket(String appid) throws Exception {
		return super.getJSTicket(appid);
	}

}
